import { fromJS } from "immutable";
import { message } from "antd";
// action types
const userTypes = {
  login: "LOGIN",
};
// 进行异步的 action async types
const userTypesAsync = {
  loginAsync: "LOGINASYNC",
};
// action creators
const userActions = {
  login: (login_value) => ({
    type: userTypesAsync.loginAsync,
    login_value,
  }),
};

// 初始值
const initState = fromJS({
  userInfo: sessionStorage.userInfo ? JSON.parse(sessionStorage.userInfo) : "",
});

// reducer
const userReducer = (state = initState, action) => {
  switch (action.type) {
    case userTypes.login:
      const userInfo = {
        username: action.payload.username,
        role: action.payload.role,
        usertoken: action.payload.access_token,
      };
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
      message.info("登录成功！");
      return fromJS({ userInfo });
    default:
      return state;
  }
};

export { userTypes, userTypesAsync, userActions, userReducer };
